<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<script>


//【示例1】惰性载入函数的设计原理与分支函数类似，下面是简单的示例。 
var addEvent = function(el, type, handle) {
    addEvent = el.addEventListener ? function(el, type, handle) {
        el.addEventListener(type, handle, false);
    } : function(el, type, handle) {
        el.attachEvent("on" + type, handle);
    };
    //在第一次执行addEvent函数时，修改了addEvent函数之后，必须执行一次。
    addEvent(el, type, handle);
}
//【示例2】下面代码使用if语句直接实现定义XMLHttpRequest实例对象。
function createXHR() {
    if( typeof XMLHttpRequest != 'undefined') {
        return new XMLHttpRequest();
    } else if( typeof ActiveXObject != 'undefined') {
        if( typeof arguments.callee.activeXString != 'string') { 
            versions = ["MSXML2.XMLHttp", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp.6.0"];
            for(var i = 0, len = versions.length; i < len; i++) {
                try {
                    var xhr = new ActiveXObject(versions[i]);
                    arguments.callee.activeXString = versions[i];
                    return xhr;
                } catch(ex) {
                    //跳过
                }
            }
        }
        return new ActiveXObject(arguments.callee.activeXString);
    } else {
        throw new Error("No XHR object available.");
    }
}
//【示例3】下面示例代码使用惰性载入函数定义XMLHttpRequest实例对象。
function createXHR() {
    if( typeof XMLHttpRequest != 'undefined') {
        createXHR = function() {
            return new XMLHttpRequest();
        };
    } else if( typeof ActiveXObject != 'undefined') {
        createXHR = function() {
            if( typeof arguments.callee.activeXString != 'string') { 
                versions = ["MSXML2.XMLHttp", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp.6.0"];
                for(var i = 0, len = versions.length; i < len; i++) {
                    try {
                        var xhr = new ActiveXObject(versions[i]);
                        arguments.callee.activeXString = versions[i];
                        return xhr;
                    } catch(ex) {
                        //跳过
                    }
                }
            }
            return new ActiveXObject(arguments.callee.activeXString);
        };
    } else {
        createXHR = function() {
            throw new Error("No XHR object available.");
        };
    }
    return createXHR();
}


</script>
</head>
<body>




</body>
</html>
